package com.admin.listener;

import com.admin.annotations.EnableNacos;
import com.admin.config.NacosConfigProcessor;
import com.admin.model.ServiceRegistryState;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.AnnotationUtils;

public class NacosApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    private ApplicationContext context;

    public NacosApplicationListener(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 获取主应用类
        Class<?> mainClass = event.getSpringApplication().getMainApplicationClass();

        // 检查主应用类是否有 @EnableNacos 注解
        if (AnnotationUtils.findAnnotation(mainClass, EnableNacos.class) != null) {
            handleEnableNacos();
            ServiceRegistryState.setNacosEnabled(true);
        }
    }

    private void handleEnableNacos() {
        // 从 Spring 上下文获取 NacosConfigProcessor Bean
        NacosConfigProcessor nacosProcessor = context.getBean(NacosConfigProcessor.class);
        // 调用 process 方法以注册服务
        nacosProcessor.process();
    }
}


